package com.hengxinguotong.zhihuichengjian.widget.view;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.AbsListView;
import android.widget.ListView;

import com.hengxinguotong.zhihuichengjian.R;


public class PullDownRefreshListView extends ListView {
	
	
	private final static String TAG = "PullDownRefreshListView";
	
	

	public PullDownRefreshListView(Context context) {
		super(context);
		init();
	}

	public PullDownRefreshListView(Context context, AttributeSet attrs) {
		super(context, attrs);
		init();
	}

	public PullDownRefreshListView(Context context, AttributeSet attrs,
								   int defStyle) {
		super(context, attrs, defStyle);
		init();
	}
	
	/**
	 * 初始话
	 */
	private void init(){
		Log.i("test", "PullDownRefreshListView");
		initFooter();
		setListener();
	}

	

	/**
	 * 初始化脚
	 */
	private void initFooter() {
		Log.i("test", "initFooter");
		footerView = View.inflate(getContext(), R.layout.pull_down_refresh_lv_footer, null);
		addFooterView(footerView);
		footerView.measure(0, 0);
		footer_height = footerView.getMeasuredHeight();
		footerView.setPadding(0, -footer_height, 0, 0);
	}

	
	/**
	 * 设置监听
	 */
	private void setListener() {
		//给ListView设置滑动监听
		setOnScrollListener(new MyOnScrollListener());
	}
	
	
	private int firstVisibleItem;//记录屏幕上显示的第一个条目
	
	//有没有在记载脚数�?
	private boolean isLoadingData = false;
	private class MyOnScrollListener implements OnScrollListener{

		//滑动状态的改变
		@Override
		public void onScrollStateChanged(AbsListView view, int scrollState) {
			if((scrollState == OnScrollListener.SCROLL_STATE_FLING ||
					scrollState == OnScrollListener.SCROLL_STATE_IDLE)&&//用户已经松手
					getLastVisiblePosition() == getAdapter().getCount() - 1 &&//已经滑动到了最后
					!isLoadingData//没有在加载数据
				){
				isLoadingData = true;//修改加载数据的状态
				//显示脚
				footerView.setPadding(0, 0, 0, 0);
				//选中最后一个条目
				setSelection(getAdapter().getCount() - 1);  
				//加载数据
				if(onPullDownRefreshListener != null){
					//加载数据
					onPullDownRefreshListener.loadFooterData();
				}else{
					//隐藏脚
					hideFooter();
				}
			}
		}

		//滑动
		@Override
		public void onScroll(AbsListView view, int firstVisibleItem,
				int visibleItemCount, int totalItemCount) {
			PullDownRefreshListView.this.firstVisibleItem = firstVisibleItem;
		}
		
	}
	
	/**
	 * 隐藏脚
	 */
	public void hideFooter(){
		footerView.setPadding(0, -footer_height, 0, 0);
		isLoadingData = false;
	}
	

	
	private OnPullDownRefreshListener onPullDownRefreshListener;

	private View footerView;

	private int footer_height;
	
	public void setOnPullDownRefreshListener(
			OnPullDownRefreshListener onPullDownRefreshListener) {
		this.onPullDownRefreshListener = onPullDownRefreshListener;
	}


	//设计接口
	public interface OnPullDownRefreshListener{
		//加载脚数数据
		public void loadFooterData();
	}
	
}
